package cn.shrek.realm;


import cn.shrek.bean.User;
import cn.shrek.service.PermissionService;
import cn.shrek.service.RoleService;
import cn.shrek.service.UserService;
import cn.shrek.vo.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;
    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户名
        String user_name=token.getPrincipal().toString();
        //根据用户名查询用户对象
        User user=this.userService.queryUserByUserName(user_name);
        //根据用户ID查询角色
        List<String> roles=this.roleService.queryRolesByUserId(user.getUser_id());
        //根据用户ID查询权限
        List<String> permissions=this.permissionService.queryPermissionsByUserId(user.getUser_id());
        if(null!=user){
            ActiverUser activerUser=new ActiverUser();
            activerUser.setUser(user);
            activerUser.setRoles(roles);
            activerUser.setPermissions(permissions);
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                    activerUser,user.getUserpwd(), ByteSource.Util.bytes(user.getUser_name()+"n&$mk12"),getName()
            );
            return info;
        }else{
            return null;
        }
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        ActiverUser activerUser= (ActiverUser) principals.getPrimaryPrincipal();
        List<String> roles = activerUser.getRoles();
        List<String> permissions = activerUser.getPermissions();
        if(null!=roles&&!roles.isEmpty()){
            info.addRoles(roles);
        }
        if(null!=permissions&&!permissions.isEmpty()){
            info.addStringPermissions(permissions);
        }
        return info;
    }
}
